﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Core.Utilities;

namespace CarLeaseManageSystem
{
    public partial class FormSearch : Form
    {
        public FormSearch()
        {
            InitializeComponent();
        }

        struct struCar
        {
            public string sCType;
            public string sCarId;
            public string sCPId;
            public string sBF;
            public Image imgCar;
        };

        CDbCar car = new CDbCar();
        List<struCar> liCar = new List<struCar>();
        private void FormSearch_Load(object sender, EventArgs e)
        {
            comBoxArea.SelectedIndex = 0;
            string seleStr;
            DataRowCollection rows;
            ListViewItem cItem;
            seleStr = "select icarid as 车编,sctype as 车型,scpid as 车牌,bbf as 报废,mcphoto as 车照 from carinfo order by bbf desc ";
            rows = car.GetDataset(seleStr).Tables[0].Rows;
            listViewCar.Items.Clear();
            liCar.Clear();
            struCar strucar;
            foreach (DataRow row in rows)
            {
                strucar = new struCar();
                strucar.sCarId = row["车编"].ToString();//汽车编号
                strucar.sCType = row["车型"].ToString();//车型
                strucar.sCPId = row["车牌"].ToString();//车牌
                strucar.imgCar = Image.FromStream(new MemoryStream((byte[])row["车照"]));
                strucar.sBF = (bool)row["报废"] ? "报废" : "活动";
                cItem = new ListViewItem(strucar.sCType);
                cItem.Tag = strucar.sCarId;
                cItem.SubItems.Add(strucar.sCPId);
                cItem.SubItems.Add(strucar.sBF);
                cItem.BackColor = (bool)row["报废"] ? Color.Red : Color.White;
                liCar.Add(strucar);
                listViewCar.Items.Add(cItem);
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "tabKH":
                    break;
                case "tabCar":
                    break;
            }
        }
        //按姓名找客户
        private void txtBoxSearName_TextChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewKeHu.Items)
                item.BackColor = Color.White;
            try
            {
                ListViewItem seleItem = listViewKeHu.FindItemWithText(txtBoxSearName.Text);
                seleItem.BackColor = Color.Blue;
                seleItem.Focused = true; seleItem.Selected = true; seleItem.Checked = true;
            }
            catch { }
        }
        //查找车辆
        private void txtBoxSearCar_TextChanged(object sender, EventArgs e)
        {
            listViewCar.Items.Clear();
            ListViewItem cItem;
            foreach (struCar ca in liCar.FindAll(FindCar))
            {
                cItem = new ListViewItem(ca.sCType);
                cItem.Tag = ca.sCarId;
                cItem.SubItems.Add(ca.sCPId);
                cItem.SubItems.Add(ca.sBF);
                cItem.BackColor = ca.sBF == "报废" ? Color.Red : Color.White;
                listViewCar.Items.Add(cItem);
            }
        }
        //查找车辆的委托方法
        private bool FindCar(struCar ca)
        {
            try
            {
                if (ca.sCType.Substring(0, txtBoxSearCar.Text.Length) == txtBoxSearCar.Text)
                    return true;
                else
                    if (ca.sCPId.Substring(0, txtBoxSearCar.Text.Length) == txtBoxSearCar.Text)
                        return true;
                    else
                        return false;
            }
            catch { return false; }
        }

        //当单击客户列表中的某项时
        string seleId = "";
        private void listViewKeHu_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
                return;
            seleId = e.Item.Tag.ToString();
            if (comBoxArea.SelectedIndex == 0)
            {
                //查看已租车的客户的租车信息
                string str = "select a.iczdid,b.sname+'('+right(b.sidcard,4)+')' as client,b.mphoto,c.sctype+'('+c.scpid+')' as car,c.mcphoto,a.drifuje," +
    "datediff('d',a.tstartdate,iif(isnull((select top 1 tnewdate from xuzuinfo where iczdid=a.iczdid order by tnewdate desc)),a.tenddate,(select top 1 tnewdate from xuzuinfo where iczdid=a.iczdid order by tnewdate desc))) as days," +
    "a.drifuje*days as hire from chuzuinfo a,kehuinfo b,carinfo c where a.ikehuid=b.ikehuid and a.icarid=c.icarid and a.bczzf=False and a.iczdid=" + seleId;
                DataRow row = car.GetDataset(str).Tables[0].Rows[0];
                txtName.Text = row["client"].ToString();
                txtCar.Text = row["car"].ToString();
                numRF.Value = (Decimal)row["drifuje"];
                numCZDays.Value = Decimal.Parse(row["days"].ToString());
                numYFJE.Value = Decimal.Parse(row["hire"].ToString());
                pictPhoto.Image =ImageHelper.MergeImg(Image.FromStream(new MemoryStream((byte[])row["mcphoto"])), Image.FromStream(new MemoryStream((byte[])row["mphoto"])));

                str = "select swzaddr,swzdetail,dwzje,twzdate,bwzzf from weizhanginfo where iczdid=" + seleId;
                DataRowCollection rows = car.GetDataset(str).Tables[0].Rows;
                if (rows.Count != 0)
                {
                    string tempStr = "";
                    int iCount = 0;
                    foreach (DataRow ro in rows)
                    {
                        tempStr += "地点：" + ro["swzaddr"].ToString() + "\t内容：" + ro["swzdetail"].ToString() + "\r\n";
                        tempStr += "罚金：" + ro["dwzje"].ToString() + "元\t日期：" + ((DateTime)ro["twzdate"]).ToLongDateString() + "\t处理：" + ((bool)ro["bwzzf"] ? "已处理" : "未处理") + "\r\n\r\n";
                        iCount++;
                    }
                    txtMore.Text = tempStr;
                    labWZ.Text = "共[" + iCount.ToString() + "]条" + " 未处理[" + iCount.ToString() + "]条";
                }
                else
                {
                    txtMore.Text = "(该客户目前尚无违章记录)";
                    labWZ.Text = "共[00]条 未处理[00]条";
                }

            }
            else
            {
                //查看已还车信息
                string str2 = "select b.sname+'('+right(b.sidcard,4)+')' as client,c.sctype+'('+c.scpid+')' as car,a.drifu,a.iczdays+a.ixzdays as days,"+
                    "a.dshifu,a.smore,a.imgkc from tuihuaninfo a,kehuinfo b,carinfo c where a.ikehuid=b.ikehuid and c.icarid=a.icarid and a.bthzf=False and a.ikehuid="+seleId;
                if (bindingSource1.DataSource != null)
                    bindingSource1 = new BindingSource();
                bindingSource1.DataSource = car.GetDataset(str2).Tables[0];
                bindingNavigator1.BindingSource = bindingSource1;
                txtName.DataBindings.Clear(); txtCar.DataBindings.Clear(); numRF.DataBindings.Clear(); numYFJE.DataBindings.Clear(); numCZDays.DataBindings.Clear();
                pictPhoto.DataBindings.Clear(); txtMore.DataBindings.Clear();
                txtName.DataBindings.Add(new Binding("Text", bindingSource1, "client"));
                txtCar.DataBindings.Add(new Binding("Text", bindingSource1, "car"));
                numCZDays.DataBindings.Add(new Binding("Value", bindingSource1, "days"));
                numRF.DataBindings.Add(new Binding("Value", bindingSource1, "drifu"));
                numYFJE.DataBindings.Add(new Binding("Value", bindingSource1, "dshifu"));
                txtMore.DataBindings.Add(new Binding("Text", bindingSource1, "smore"));
                Binding b = new Binding("Image", bindingSource1, "imgkc");
                b.Format += new ConvertEventHandler(b_Format);
                pictPhoto.DataBindings.Add(b);
                labWZ.Text = "[车辆已还,所有违章均已处理]";
            }
        }

        void b_Format(object sender, ConvertEventArgs e)
        {
            Bitmap bt = new Bitmap(new MemoryStream((byte[])e.Value));
            e.Value = bt;
        }

        private void comBoxArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            string seleStr = "";
            DataRowCollection rows;
            ListViewItem cItem;
            switch (comBoxArea.SelectedIndex)
            {
                //出租中客户,同一个客户不可能出现两次活动的出租记录
                case 0:
                    seleStr = "select a.iczdid,b.sname+'('+right(b.sidcard,4)+')' as client,b.mphoto,b.blogout from chuzuinfo a,kehuinfo b where a.ikehuid=b.ikehuid and a.bczzf=False";
                    rows = car.GetDataset(seleStr).Tables[0].Rows;
                    listViewKeHu.Items.Clear();
                    if (rows.Count != 0)
                    {
                        foreach (DataRow row in rows)
                        {
                            //创建一个新列表项
                            cItem = new ListViewItem(row["client"].ToString());//项标题
                            cItem.Tag = row["iczdid"].ToString();//Tag属性 出租单编号
                            cItem.SubItems.Add((bool)row["blogout"] ? "注销" : "活动");//添加子项
                            listViewKeHu.Items.Add(cItem);//将项添加到列表中
                        }
                    }
                    break;
                //已还车客户
                case 1:
                    seleStr = "select distinct a.ikehuid,b.sname+'('+right(b.sidcard,4)+')' as client,b.blogout from tuihuaninfo a,kehuinfo b where a.ikehuid=b.ikehuid and a.bthzf=False";
                    rows = car.GetDataset(seleStr).Tables[0].Rows;
                    listViewKeHu.Items.Clear();
                    if (rows.Count != 0)
                    {
                        foreach (DataRow row in rows)
                        {
                            //创建一个新列表项
                            cItem = new ListViewItem(row["client"].ToString());//项标题
                            cItem.Tag = row["ikehuid"].ToString();//Tag属性 客户ID
                            cItem.SubItems.Add((bool)row["blogout"] ? "注销" : "活动");//添加子项
                            listViewKeHu.Items.Add(cItem);//将项添加到列表中
                        }
                    }
                    break;
            }
        }

        private void listViewCar_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
                return;          
            string sCarId = e.Item.Tag.ToString();  
            textBoxCar.Text = e.Item.Text;
            pictureBox1.Image = Image.FromStream(new MemoryStream((byte[])car.GetDataset("select mcphoto from carinfo where icarid="+sCarId).Tables[0].Rows[0]["mcphoto"]));
            string yiSR = "select sum(dshifu) as 已收入 from tuihuaninfo where icarid="+sCarId;
            //从正在出租的数据库表中查找计算机,这个月从开始到今天的租金和从开始租车到今天的累计租金,如果该车是本月中的某一天租出,则从那一天开始计算到今天的租金和累计租金(此时租金和累计租金相同)
            string bengYueSR = "select datediff('d',iif(cdate(cstr(datepart('yyyy',now()))+'-'+cstr(datepart('m',now()))+'-1')<tstartdate,tstartdate,cdate(cstr(datepart('yyyy',now()))+'-'+cstr(datepart('m',now()))+'-1')),now())*drifuje as 本月收入,"+
                "datediff('d',tstartdate,now())*drifuje as 累计租金 from chuzuinfo where bczzf=False and icarid=" + sCarId;
            decimal bysr = 0,yisr=0,leiji=0;
            try
            {
                bysr = Decimal.Parse(car.GetDataset(bengYueSR).Tables[0].Rows[0]["本月收入"].ToString());
                leiji=Decimal.Parse(car.GetDataset(bengYueSR).Tables[0].Rows[0]["累计租金"].ToString());
            }
            catch { }
            try
            {
                yisr = Decimal.Parse(car.GetDataset(yiSR).Tables[0].Rows[0]["已收入"].ToString());
            }
            catch { }
            numBYSR.Value = bysr;
            numTotal.Value= (bysr==leiji?leiji:bysr+leiji) + yisr;
            string seleWZ = "select b.sname+'('+right(b.sidcard,4)+')' as client,a.swzaddr,a.swzdetail,a.dwzje,a.twzdate,a.bwzzf from weizhanginfo a,kehuinfo b where a.ikehuid=b.ikehuid and a.icarid="+sCarId+" order by a.twzdate";
            DataRowCollection rows = car.GetDataset(seleWZ).Tables[0].Rows;
            if (rows.Count != 0)
            {
                string s = ""; int i = 0; int nodeal = 0;
                foreach (DataRow r in rows)
                {
                    s += "==========================违章" + (i + 1).ToString() + "==========================\r\n";
                    s += "客户:" + r["client"].ToString() + "\r\n违章:" + r["swzaddr"].ToString() + r["swzdetail"].ToString() + "\r\n";
                    s += "罚金:" + r["dwzje"].ToString() + "元\t日期:" + ((DateTime)r["twzdate"]).ToLongDateString() + "\t处理:" + ((bool)r["bwzzf"] ? "已处理" : "未处理") + "\r\n";
                    if (!(bool)r["bwzzf"])
                        nodeal++;
                    i++;
                }
                labelWZ.Text = "共[" + i.ToString() + "]条 未处理[" + nodeal.ToString() + "]条";
                txtBoxWz.Text = s;
            }
            else
            {
                txtBoxWz.Text = "";
                labelWZ.Text = "共[00]条 未处理[00]条";
            }
            try
            {
                labCZTimes.Text ="共["+ car.GetDataset("select count(*) as times from chuzuinfo where icarid=" + sCarId).Tables[0].Rows[0]["times"].ToString()+"]次";
            }
            catch { labCZTimes.Text = "共[00]次"; }
        }
    }
}
